use regex::Regex;
use std::fs::{self};
use std::io::Write;
use std::io::{self};

#[tauri::command]
pub fn set_config(value: String, target: String) {
    let file_path = "clewd/config.js";
    // 读取文件内容
    let file_content = match fs::read_to_string(file_path) {
        Ok(content) => content,
        Err(e) => {
            eprintln!("Error reading file: {}", e);
            return;
        }
    };
    // 使用正则表达式替换 Cookie 的值
    let pattern = format!(
        r#""{}":\s*("(?:[^"]*)"|-?\d+(\.\d+)?|true|false|null)"#,
        target
    );
    let regex = Regex::new(&pattern).unwrap();
    let new_pattern = format!(r#""{}": "{}""#, target, value);
    let updated_content = regex.replace_all(&file_content, new_pattern);
    // 将修改后的内容写回文件
    if let Err(e) = write_to_file(file_path, &updated_content.to_string()) {
        eprintln!("Error writing to file: {}", e);
    }
}

fn write_to_file(file_path: &str, content: &str) -> io::Result<()> {
    let mut file = fs::File::create(file_path)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}
